package com.tencreat.service.account.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencreat.common.core.HttpResult;
import com.tencreat.common.core.domain.BaseEntity;
import com.tencreat.common.core.domain.entity.SysUser;
import com.tencreat.common.core.domain.model.LoginUser;
import com.tencreat.common.core.domain.model.ReqIdParam;
import com.tencreat.common.core.domain.model.ReqIdsParam;
import com.tencreat.common.enums.BalanceBusinessType;
import com.tencreat.common.enums.BalanceTypeEnum;
import com.tencreat.common.enums.mall.AllEnum;
import com.tencreat.common.utils.RabbitSendUtils;
import com.tencreat.domain.account.CommonWithdrawConfig;
import com.tencreat.domain.account.MallUser;
import com.tencreat.domain.account.dto.AdminAuditResultDTO;
import com.tencreat.domain.account.dto.ApiWithdrawDTO;
import com.tencreat.domain.mall.SupplierWithdrawAudit;
import com.tencreat.domain.mall.vo.AuditResultVO;
import com.tencreat.domain.mall.vo.RrsAuditResultVO;
import com.tencreat.mapper.mall.SupplierWithdrawAuditMapper;
import com.tencreat.service.account.IAccountWithdrawInfoService;
import com.tencreat.service.account.IMallUserService;
import com.tencreat.service.account.ISupplierWithdrawAuditService;
import com.tencreat.service.system.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 供应商提现记录Service业务层处理
 *
 * @author tencreat
 * @date 2022-03-17
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SupplierWithdrawAuditServiceImpl extends ServiceImpl<SupplierWithdrawAuditMapper, SupplierWithdrawAudit> implements ISupplierWithdrawAuditService {
    @Autowired
    private IMallUserService mallUserService;
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IAccountWithdrawInfoService accountWithdrawInfoService;
    @Autowired
    private RabbitSendUtils rabbitSendUtils;
    /**
     * 查询供应商提现记录
     *
     * @param id 供应商提现记录ID
     * @return 供应商提现记录
     */
    @Override
    public SupplierWithdrawAudit selectSupplierWithdrawAuditById(ReqIdParam id) {
        return baseMapper.selectById(id.getId());
    }

    /**
     * 查询供应商提现记录列表
     *
     * @param supplierWithdrawAudit 供应商提现记录
     * @return 供应商提现记录
     */
    @Override
    public List<SupplierWithdrawAudit> selectSupplierWithdrawAuditList(SupplierWithdrawAudit supplierWithdrawAudit) {
        return baseMapper.selectList(Wrappers.query(supplierWithdrawAudit));
    }

    /**
     * 新增供应商提现记录
     *
     * @param supplierWithdrawAudit 供应商提现记录
     * @return 结果
     */
    @Override
    public int insertSupplierWithdrawAudit(SupplierWithdrawAudit supplierWithdrawAudit) {
        supplierWithdrawAudit.setCreateTime(LocalDateTime.now());
        return baseMapper.insert(supplierWithdrawAudit);
    }

    /**
     * 修改供应商提现记录
     *
     * @param supplierWithdrawAudit 供应商提现记录
     * @return 结果
     */
    @Override
    public int updateSupplierWithdrawAudit(SupplierWithdrawAudit supplierWithdrawAudit) {
        supplierWithdrawAudit.setUpdateTime(LocalDateTime.now());
        return baseMapper.updateById(supplierWithdrawAudit);
    }

    /**
     * 批量删除供应商提现记录
     *
     * @param ids 需要删除的供应商提现记录ID
     * @return 结果
     */
    @Override
    public int deleteSupplierWithdrawAuditByIds(ReqIdsParam ids) {
        return baseMapper.deleteBatchIds(ids.getId());
    }

    /**
     * 删除供应商提现记录信息
     *
     * @param id 供应商提现记录ID
     * @return 结果
     */
    @Override
    public int deleteSupplierWithdrawAuditById(ReqIdParam id) {
        return baseMapper.deleteById(id.getId());
    }

    @Override
    public void auditResult(AdminAuditResultDTO param) {
        SupplierWithdrawAudit byId = getById(param.getId());
        byId.setAuditTime(LocalDateTime.now());
        byId.setResult(param.getResult());
        byId.setAuditOpinion(param.getAuditOpinion());
        if (param.getResult() == 2) {
           rabbitSendUtils.sendBalanceMessage(byId.getUuid(),byId.getValue(),AllEnum.BalanceChangeTypeEnums.INCOME.getType(), BalanceBusinessType.WITHDRAW_FAIL,"","",BalanceTypeEnum.FINANCE);
        }
        updateById(byId);
    }

    @Override
    public RrsAuditResultVO priceStatistics() {
        return baseMapper.priceStatistics();
    }

    @Override
    public AuditResultVO priceStatisticsV2(){
        BigDecimal auditAmount = baseMapper.auditAmount();
        BigDecimal waitAmount = baseMapper.waitAmount();
        BigDecimal refuseAmount = baseMapper.refuseAmount();
        Integer waitCount = lambdaQuery().eq(SupplierWithdrawAudit::getResult,0).count();
        Integer succCount = lambdaQuery().eq(SupplierWithdrawAudit::getResult,1).count();
        Integer failCount = lambdaQuery().eq(SupplierWithdrawAudit::getResult,2).count();
        int totalCount = (waitCount != null ? waitCount : 0) + (succCount != null ? succCount : 0) + (failCount != null ? failCount : 0);
        AuditResultVO auditResultVO = new AuditResultVO();
        auditResultVO.setAuditAmount(auditAmount);
        auditResultVO.setRefuseAmount(refuseAmount);
        auditResultVO.setWaitAmount(waitAmount);
        auditResultVO.setAuditCount(succCount);
        auditResultVO.setRefuseCount(failCount);
        auditResultVO.setWaitCount(waitCount);
        auditResultVO.setTotalCount(totalCount);

        return auditResultVO;
    }

    @Override
    public HttpResult<String> withdraw(ApiWithdrawDTO vo, LoginUser loginUser) {
        Long uuid = loginUser.getAccountLogin().getUuid();

        MallUser one = mallUserService.lambdaQuery().eq(MallUser::getUuid, uuid).one();
        if (StringUtils.isBlank(one.getPayPassword())) {
            return HttpResult.error("请先设置支付密码");
        }
        if (!vo.getPassword().equals(one.getPayPassword())) {
            return HttpResult.error("密码错误");
        }
        if (BigDecimal.ZERO.compareTo(vo.getAmount()) > 0) {
            return HttpResult.error("余额不可为负数");
        }
        //现有余额
        BigDecimal earnings = one.getFinance();
        if (earnings.compareTo(vo.getAmount()) < 0) {
            return HttpResult.error("余额不足");
        }

        CommonWithdrawConfig commonWithdrawConfig = accountWithdrawInfoService.selectWithdrawInfo(2,vo.getUserType());

        if (commonWithdrawConfig.getIsHundredWithdraw() == 1) {
            BigDecimal yu = vo.getAmount().divideAndRemainder(BigDecimal.valueOf(100))[1];
            if (BigDecimal.ZERO.compareTo(yu) != 0) {
                return HttpResult.error("请输入整百的金额");
            }
        }

        if (commonWithdrawConfig.getMinWithdraw().compareTo(vo.getAmount()) > 0) {
            return HttpResult.error("最低提现" + commonWithdrawConfig.getMinWithdraw());
        }

        if (earnings.subtract(vo.getAmount()).compareTo(commonWithdrawConfig.getMinKeep()) < 0) {
            return HttpResult.error("最低需保留" + commonWithdrawConfig.getMinWithdraw());
        }
        rabbitSendUtils.sendBalanceMessage(one.getUuid(),vo.getAmount(),AllEnum.BalanceChangeTypeEnums.EXPENDITURE.getType(), BalanceBusinessType.WITHDRAW,vo.getWithdrawType().toString(),"", BalanceTypeEnum.FINANCE);

        return HttpResult.ok();

    }

    @Override
    public List<SupplierWithdrawAudit> queryWithdrawRecord(Long uuid) {
        return lambdaQuery().eq(SupplierWithdrawAudit::getUuid, uuid).orderByDesc(BaseEntity::getCreateTime).list();
    }

    @Override
    public IPage<SupplierWithdrawAudit> supplierList(SupplierWithdrawAudit supplierWithdrawAudit) {
        return baseMapper.supplierList(new Page<>(supplierWithdrawAudit.getPageNum(), supplierWithdrawAudit.getPageSize()), supplierWithdrawAudit);
    }

    @Override
    public BigDecimal value(Long uuid) {
        return baseMapper.value(uuid);
    }
}
